<template>
  <div>
    <a-spin :loading="loading" style="width: 100%">
      <div v-if="props.title === '购物车'" class="">
        <div class="shopping-cart-box" v-for="(item, index) in cartData" @click="linkTo('/cart')" :key="index">
          <div class="shopping-cart-img mr_10">
            <img :src="item.goodsSku.thumbnail" style="width: 90px;height: 90px;" class="hover-pointer"/>
          </div>
          <div class="shopping-cart-info">
            <div class="ellipsis ellipsis-1">{{ item.goodsSku.goodsName }}</div>
            <div class="price-color">{{ unitPrice(item.purchasePrice, '￥') }}<span class="light-text-color ml_10">×{{ item.num }}</span></div>
            <div class="del hover-color fontsize-12" @click="delGoods(item.goodsSku.id)">删除</div>
          </div>
        </div>
        <a-button long status="danger" type="primary" @click="linkTo('/cart')" class="mt_20">去购物车结算</a-button>
      </div>
      <div v-if="props.title === '我的订单'" class="order-con">
        <div v-for="(order,orderIndex) in orderData" :key="orderIndex" class="order-data">
          <div class="order-status"><span>{{filterOrderStatus(order.orderStatus)}}</span><span>{{order.createTime}}</span></div>
          <div class="goods-img">
            <img :src="img.image" @click="linkTo(`/goodsDetail?skuId=${img.skuId}&goodsId=${img.goodsId}`)" v-for="(img,imgIndex) in order.orderItems" :key="imgIndex" width="40" height="40" alt="">
          </div>
          <div class="order-handle">
            <span class="price-color">{{ unitPrice(order.flowPrice, "￥") }}</span>
            <span class="hover-color" @click="linkTo(`/user/home/orderCenter/orderDetail?sn=${order.sn}`)">查看订单</span>
          </div>
        </div>
        <a-button long status="danger" type="primary" @click="linkTo('/user/home/orderCenter/myOrder')" class="mt_20">查看全部订单</a-button>
      </div>
      <div v-if="props.title === '优惠券'" class="coupon-con">
        <div class="coupon-list">
          <div v-for="(item, index) in couponData" :key="index" class="coupon-item">
            <div class="c-left">
              <div>
                <span v-if="item.couponType === 'PRICE'" class="fontsize_12 price-color">{{ unitPrice(item.price, '￥') }}</span>
                <span v-if="item.couponType === 'DISCOUNT'" class="fontsize_12 price-color"><span class="fontsize-18">{{ item.couponDiscount }}</span>折</span>
                <span class="describe">满{{ item.consumeThreshold }}元可用</span>
              </div>
              <div style="line-height: 18px;margin: 10px 0;">使用范围：{{ useScope(item.scopeType, item.storeName) }}</div>
              <div style="color: #999999; font-size: 13px;">有效期：{{ item.endTime }}</div>
            </div>
            <b></b>
            <a class="c-right hover-pointer" @click="receive(item)">立即领取</a>
            <i class="circle-top"></i>
            <i class="circle-bottom"></i>
          </div>
        </div>
      </div>
      <div v-if="props.title === '我的足迹'" class="tracks-con">
        <div v-for="(track,trackIndex) in tracksData" :key="trackIndex">
          <img :src="track.thumbnail" :alt="track.thumbnail" @click="linkTo(`/goodsDetail?skuId=${track.id}&goodsId=${track.goodsId}`)" width="100" height="100">
          <div @click="addToCart(track.id)">加入购物车</div>
          <p class="ellipsis ellipsis-1 hover-color hover-pointer" @click="linkTo(`/goodsDetail?skuId=${track.id}&goodsId=${track.goodsId}`)">{{ track.goodsName }}</p>
          <p class="price-color">{{unitPrice(track.price, '￥')}}</p>
        </div>
        <a-button long status="danger" type="primary" @click="linkTo('/user/home/memberCenter/myTracks')" class="mt_20">查看更多>></a-button>
      </div>
      <div v-if="props.title === '我的收藏'" class="collect-con">
        <div v-for="(collect,collectIndex) in collectData" :key="collectIndex">
          <img :src="collect.image" :alt="collect.image" @click="linkTo(`/goodsDetail?skuId=${collect.skuId}&goodsId=${collect.goodsId}`)" width="100" height="100">
          <div @click="addToCart(collect.skuId)">加入购物车</div>
          <span class="del-icon" @click.stop="handleCancelCollect(collect.skuId)">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24">
              <g fill="none" fill-rule="evenodd">
              <path d="M24 0v24H0V0zM12.593 23.258l-.011.002l-.071.035l-.02.004l-.014-.004l-.071-.035c-.01-.004-.019-.001-.024.005l-.004.01l-.017.428l.005.02l.01.013l.104.074l.015.004l.012-.004l.104-.074l.012-.016l.004-.017l-.017-.427c-.002-.01-.009-.017-.017-.018m.265-.113l-.013.002l-.185.093l-.01.01l-.003.011l.018.43l.005.012l.008.007l.201.093c.012.004.023 0 .029-.008l.004-.014l-.034-.614c-.003-.012-.01-.02-.02-.022m-.715.002a.023.023 0 0 0-.027.006l-.006.014l-.034.614c0 .012.007.02.017.024l.015-.002l.201-.093l.01-.008l.004-.011l.017-.43l-.003-.012l-.01-.01z"/><path fill="#666666" d="M14.28 2a2 2 0 0 1 1.897 1.368L16.72 5H20a1 1 0 1 1 0 2l-.003.071l-.867 12.143A3 3 0 0 1 16.138 22H7.862a3 3 0 0 1-2.992-2.786L4.003 7.07A1.01 1.01 0 0 1 4 7a1 1 0 0 1 0-2h3.28l.543-1.632A2 2 0 0 1 9.721 2zM9 10a1 1 0 0 0-.993.883L8 11v6a1 1 0 0 0 1.993.117L10 17v-6a1 1 0 0 0-1-1m6 0a1 1 0 0 0-1 1v6a1 1 0 1 0 2 0v-6a1 1 0 0 0-1-1m-.72-6H9.72l-.333 1h5.226z"/></g>
            </svg>
          </span>
          <p class="ellipsis ellipsis-1 hover-color hover-pointer" @click="linkTo(`/goodsDetail?skuId=${collect.skuId}&goodsId=${collect.goodsId}`)">{{ collect.goodsName }}</p>
          <p class="price-color">{{unitPrice(collect.price, '￥')}}</p>
        </div>
        <a-button long status="danger" type="primary" @click="linkTo('/user/home/memberCenter/myFavorites')" class="mt_20">查看更多>></a-button>
      </div>
    </a-spin>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { Modal, Message } from '@arco-design/web-vue';
  import { unitPrice } from '@/utils/filters';
  import storage from '@/utils/storage';
  import Cookies from 'js-cookie';
  import { cartGoodsAll, delCartGoods, addCartGoods, cartCount } from '@/api/cart';
  import { getOrderList } from '@/api/order';
  import { couponList, receiveCoupon, tracksList, collectList, cancelCollect } from '@/api/member';
  import { orderStatusList } from '../../pages/user/home/enumeration.js';

  /**
   * 接收父组件传值
   */
  const props = defineProps({
    // 验证码类型
    title: {
      type: String,
      default: '',
    },
  });
  const router = useRouter();
  const loading = ref(false); // 控制spin显隐
  const cartData = ref<Array<any>>([]); // 购物车列表
  const couponData = ref<Array<any>>([]); // 优惠券列表
  const orderData = ref<Array<any>>([]); // 订单列表
  const collectData = ref<Array<any>>([]); // 收藏列表
  const tracksData = ref<Array<any>>([]); // 足迹列表

  // 获取购物车列表
  const getCartList = () => {
    loading.value = true;
    cartGoodsAll().then(res => {
      loading.value = false;
      cartData.value = res.data.result.skuList;
    }).catch(() => { loading.value = false })
  };
  // 删除商品
  const delGoods = (id: any) => {
    delCartGoods({ skuIds: id }).then((res) => {
      if (res.data.success) {
        Message.success('删除成功');
        getCartList();
        cartCount().then(res => {
          storage.setCartNum(res.data.result);
          Cookies.set("cartNum",res.data.result);
        })
      } else {
        Message.error(res.data.message);
      }
    });
  };
  // 获取订单列表
  const getOrder = () => {
    loading.value = true;
    const params = { pageNumber: 1, pageSize: 10, tag: 'ALL' };
    getOrderList(params).then(res => {
      loading.value = false;
      if (res.data.success) {
        orderData.value = res.data.result.records;
      }
    }).catch(() => { loading.value = false })
  };
  // 获取足迹列表
  const getTracksList = () => {
    const params = {pageNumber: 1, pageSize: 20};
    loading.value = true;
    tracksList(params).then(res => {
      tracksData.value = res.data.result.records;
      loading.value = false
    }).catch(() => { loading.value = false })
  };
  // 获取优惠券列表
  const getCouponList = () => {
    loading.value = true;
    const params = { pageNumber: 1, pageSize: 10 };
    couponList(params).then(res => {
      loading.value = false;
      if (res.data.success) {
        couponData.value = res.data.result.records;
      }
    }).catch(() => { loading.value = false })
  };
  // 获取收藏列表
  const getCollectList = () => {
    const params = { pageNumber: 1, pageSize: 10, type: 'GOODS' };
    loading.value = true;
    collectList(params).then(res => {
      loading.value = false;
      collectData.value = res.data.result.records;
    }).catch(() => { loading.value = false })
  };
  const linkTo = (url: any) => {
    let routeUrl = router.resolve(url);
    window.open(routeUrl.href, "_blank");
  };
  const filterOrderStatus = (status: any) => { // 获取订单状态中文
    const ob = orderStatusList.filter(e => { return e.status === status });
    return ob && ob[0] ? ob[0].name : status
  };
  // 根据字段返回 优惠券适用范围
  const useScope = (type: any, storeName: any) => {
    let shop = "平台";
    let goods = "全部商品";
    if (storeName !== "platform") shop = storeName;
    switch (type) {
      case "ALL":
        goods = "全部商品";
        break;
      case "PORTION_GOODS":
        goods = "部分商品";
        break;
      case "PORTION_GOODS_CATEGORY":
        goods = "部分分类商品";
        break;
    }
    return `${shop}${goods}可用`;
  };
  // 领取优惠券
  const receive = (item: any) => {
    receiveCoupon(item.id).then(res => {
      if (res.data.success) {
        Modal.confirm({
          title: '领取优惠券',
          content: `优惠券领取成功，可到我的优惠券页面查看`,
          okButtonProps: {type: "primary", status: "danger"},
          okText: '我的优惠券',
          cancelText: '立即使用',
          onOk: () => {
            router.push('/user/home/userCenter/coupons');
          },
          onCancel: () => {
            if (item.storeId !== '0') {
              router.push({path: '/merchant', query: {id: item.storeId}})
            } else {
              if (item.scopeType === 'PORTION_GOODS_CATEGORY') {
                router.push({path: '/goodsList', query: {categoryId: item.scopeId}})
              } else {
                router.push({path: '/goodsList'})
              }
            }
          }
        });
      }
    })
  };
  // 添加商品到购物车
  const addToCart = (id: any) => {
    const params = { num: 1, skuId: id };
    loading.value = true;
    addCartGoods(params).then(res => {
      loading.value = false;
      if (res.data.success) {
        Message.success('商品已成功添加到购物车')
      } else {
        Message.warning(res.data.message);
      }
    }).catch(() => { loading.value = false });
  };
  // 取消商品收藏
  const handleCancelCollect = (id: any) => {
    cancelCollect('GOODS', id).then(res => {
      if (res.data.success) {
        Message.success('取消收藏成功');
        getCollectList();
      }
    })
  };

  watch(() => props.title, (val) => {
    switch (val) {
      case '购物车': getCartList();
        break;
      case '我的订单': getOrder();
        break;
      case '我的足迹': getTracksList();
        break;
      case '优惠券': getCouponList();
        break;
      case '我的收藏': getCollectList();
        break;
    }
  },{ immediate: true, deep: true })
</script>

<style scoped lang="less">
  /* 购物车列表 */
  .shopping-cart-box {
    padding: 6px;
    cursor: pointer;
    display: flex;
    align-items: center;
    border-bottom: 1px #ccc dotted;
    .shopping-cart-img {
      flex-shrink: 0;
      width: 90px;
      height: 90px;
    }
    .shopping-cart-info {
      width: 100%;
      > div {
        height: 22px;
        line-height: 22px;
        font-size: 13px;
      }
      .del {
        color: #666666;
        text-align: right;
      }
    }
  }
  /* 订单列表 */
  .order-con{
    .order-data {
      margin: 0 0 16px;
      background-color: #fff;
      color: @text_color;
      .order-status {
        display: flex;
        background-color: #F5F5F7;
        border-radius: 3px 3px 0 0;
        justify-content: space-between;
        padding: 0 10px;
      }
      .goods-img {
        padding-left: 4px;
        padding-top: 4px;
        img{
          border: 1px solid #eee;
          margin-right: 10px;
          &:hover{
            cursor: pointer;
          }
        }
      }
      .order-handle{
        display: flex;
        justify-content: space-between;
        padding: 0 10px;
        border-top: 1px solid #eee;
      }
    }
  }
  /* 优惠券列表 */
  .coupon-con {
    .coupon-list {
      max-height: 250px;
      flex-wrap: wrap;
      .coupon-item {
        width: 250px;
        height: 125px;
        margin-right: 10px;
        margin-bottom: 15px;
        box-sizing: border-box;
        margin-left: 10px;
        position: relative;
        border: 1px solid #eee;
        .c-left {
          padding: 10px 40px 10px 10px;
          .describe {
            background-color: #fff4ec;
            color: #F31947;
            padding: 0 5px;
            margin-left: 10px;
            font-size: 13px;
          }
        }
        .c-right {
          width: 30px;
          height: 125px;
          text-align: center;
          box-sizing: border-box;
          padding: 18px 8px;
          position: absolute;
          right: 0;
          top: 0;
          background-color: #F31947;
          color: #fff;
          font-size: 14px;
        }
        b {
          position: absolute;
          z-index: 2;
          top: 0;
          display: block;
          width: 3px;
          height: 100%;
          background: url("../../assets/images/small-circle.png") top left repeat-y;
          right: 28px;
        }
        i {
          position: absolute;
          width: 15px;
          height: 15px;
          right: 22px;
          border: 1px solid #eee;
          background-color: #fff;
          border-radius: 20px;
          &:after {
            content: "";
            position: absolute;
            width: 18px;
            height: 18px;
            left: -2px;
            background-color: #fff;
          }
        }
        i.circle-top {
          top: -10px;
          &::after {top: -8px;}
        }
        i.circle-bottom {
          bottom: -10px;
          &::after {bottom: -8px;}
        }
        .used {
          position: absolute;
          top: 60px;
          right: 40px;
          width: 50px;
          height: 50px;
        }
      }
    }
  }
  /* 我的足迹 我的收藏 */
  .tracks-con, .collect-con {
    display: flex;
    flex-wrap: wrap;
    font-size: 13px;
    > div {
      width: 49%;
      height: 140px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      position: relative;
      box-sizing: border-box;
      margin-bottom: 8px;
      &:hover{ div,.del-icon{display: block;} }
      div{
        display: none;
        position: absolute;
        bottom: 40px;
        width: 100px;
        background-color: #666;
        color: #fff;
        text-align: center;
        &:hover{background-color: @theme_color;cursor: pointer;}
      }
      .del-icon{
        display: none;
        font-size: 20px;
        position: absolute;
        width: 30px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        right: 12px;
        top: 0;
        cursor: pointer;
        color: @theme_color;
      }
      p {margin: 0;}
    }
    > div:nth-of-type(2n+1) {
      margin-right: 2%;
    }
  }
</style>
